/*
 * HttpMessageParser.cpp
 *
 *  Created on: 2018年7月3日
 *      Author: zhengboyuan
 */

#include "HttpMessageParser.h"
#include <errno.h>
#include "CLog.h"

HttpMessageParser::HttpMessageParser():
    HttpParser(HTTP_BOTH),
	m_complete()
{
}

HttpMessageParser::~HttpMessageParser()
{
}

int HttpMessageParser::parse(const char* buffer, size_t size, HttpMessageHandler handler)
{
	if (!buffer || size == 0)
	{
		return 0;
	}

    int count = execute(buffer, size);
    if (count == 0)
    {
		CLog::warning("parse return 0. buffer size: %d\n", size);
        reset();
        return 0;
    }

    m_buffer.append(buffer, count);

    if (m_complete)
    {
        handler(m_message, m_buffer);

        m_parser.http_errno = 0;
        //reset();
    }

    return count;
}

int HttpMessageParser::onMessageBegin()
{
    m_buffer.clear();
    m_message.clear();

    m_complete = false;

    return 0;
}

int HttpMessageParser::onUrl(const char* data, size_t size)
{
	m_message.m_url.append(data, size);
	m_message.m_method = http_method_str((http_method)m_parser.method);
    return 0;
}

int HttpMessageParser::onHeader(const std::string& field, const std::string& value)
{
    m_message.m_header[field] = value;

    return 0;
}

int HttpMessageParser::onHeadersComplete()
{
    return 0;
}

int HttpMessageParser::onBody(const char* data, size_t size)
{
    m_message.m_body.append(data, size);
    return 0;
}

int HttpMessageParser::onMessageComplete()
{
	if (m_message.isResponse())
	{
		m_message.m_status = m_parser.status_code;
	}

	m_complete = true;

    return 1;
}

int HttpMessageParser::onError(int code)
{
    return EINVAL;
}

void HttpMessageParser::reset()
{
    HttpParser::reset();

	m_buffer.clear();
	m_message.clear();
}

bool HttpMessageParser::isError() const
{
    return (m_errorCode != 0);
}
